import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/authStore.js'

let authStore = null

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
})

instance.interceptors.request.use(
  function (config) {
    console.log(config)

    if (authStore == null) {
      authStore = useAuthStore()
    }
    if (!config.isPublic) {
      config.headers.Authorization = 'Bearer ' + authStore.token
    }

    return config
  },
  function (error) {
    ElMessage.error('程序运行错误')
    return Promise.reject(error)
  },
)

instance.interceptors.response.use(
  function (response) {
    let { msg, status, data } = response.data
    if (status >= 400) {
      ElMessage.error(msg)
      return Promise.reject(new Error(msg))
    } else {
      if (status != 200) {
        ElMessage.success(msg)
      }
      return data
    }
  },
  function (error) {
    ElMessage.error('请求失败')
    return Promise.reject(error)
  },
)

export default instance
